//
//  EncryptionModule.m
//  XYLib
//
//  Created by Richard on 2019/3/21.
//  Copyright © 2019年 XY. All rights reserved.
//
#import <CommonCrypto/CommonDigest.h>
#import "EncryptionModule.h"

#if JWT
#import "JWTAlgorithmFactory.h"
#import <JWT/JWT.h>
#import "JWT.h"
#endif

@implementation EncryptionModule
#if JWT
WX_EXPORT_METHOD_SYNC(@selector(JWTCode:))
#endif
//MARK:大文件的MD5加密
-(NSString*)fileMD5:(NSString*)path
{
    NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
    if( handle== nil ) return @"ERROR GETTING FILE MD5"; // file didnt exist
    
    CC_MD5_CTX md5;
    
    CC_MD5_Init(&md5);
    
    BOOL done = NO;
    while(!done)
    {
        NSData* fileData = [handle readDataOfLength:256];
        //        CHUNK_SIZE
        CC_MD5_Update(&md5, [fileData bytes], (unsigned int)[fileData length]);
        if( [fileData length] == 0 ) done = YES;
    }
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5_Final(digest, &md5);
    NSString* s = [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                   digest[0], digest[1],
                   digest[2], digest[3],
                   digest[4], digest[5],
                   digest[6], digest[7],
                   digest[8], digest[9],
                   digest[10], digest[11],
                   digest[12], digest[13],
                   digest[14], digest[15]];
    return s;
}

#if JWT
-(NSString *)jwtSign:(NSDictionary *)info{
    NSString *type = @"HS256";//加密方式（默认:HS256）
    if (info[@"type"]) {
        type = info[@"type"];
    }
    NSString *secret = info[@"secret"];//服务器机密key
    NSInteger time = [info[@"timeStamp"] integerValue];//间隔时间（秒）
    NSDictionary *payload = info[@"payload"];//加密的信息
    NSString *startStamp = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];//有效期开始时间
    NSDate *date = [[NSDate date] dateByAddingTimeInterval:time];
    NSString *endStamp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];//有效期结束时间
    [payload setValue:startStamp forKey:@"iat"];
    [payload setValue:endStamp forKey:@"exp"];
    id<JWTAlgorithm> algorithm = [JWTAlgorithmFactory algorithmByName:type];
    NSString * jwt = [JWTBuilder encodePayload:payload].secret(secret).algorithm(algorithm).encode;
    return jwt;
}
#endif
@end
